﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Sitecore.Data.Items;
using System.Xml;
using Sitecore.Data.Fields;
using Sitecore.Data;

using SitecoreTranslation.Integration.Settings;

namespace SitecoreTranslation.Integration
{
	public class ExportAction : BaseAction
	{

		public ExportAction(String ExportFileName, String DataBaseName, String ItemPath)
			: base(ExportFileName, DataBaseName, ItemPath)
		{
		}

		public void Execute()
		{
			//Use a security disabler to allow changes

			using (new Sitecore.SecurityModel.SecurityDisabler())
			{
				Item item = Database.Items[_itemPath]; 

				XmlDocument document = new XmlDocument();

				XmlDeclaration dec = document.CreateXmlDeclaration("1.0", null, null);
				document.AppendChild(dec);// Create the root element

				XmlElement Rootelement = document.CreateElement(RootName);
				document.AppendChild(Rootelement);

				//Settings Setup

				
				XmlElement itemNode = document.CreateElement(ItemName);
				itemNode.SetAttribute(ItemId,  item.ID.ToString());
				itemNode.SetAttribute("Name",  item.Name);

				Rootelement.AppendChild(itemNode);

				
				

				//TODO: 
				TranslationSettings settings = new TranslationSettings();
				settings.SourceLanguage = item.Language.Name;
				settings.TargetLanguage = item.Languages[1].Name;


				itemNode.AppendChild(settings.Serialize(document));

				foreach (Field field in item.Fields)
				{
					FieldToXml(field, document, itemNode);
				}

				document.Save(_fileName);
			}
		}

		private static void FieldToXml(Field field,XmlDocument document, XmlElement owner)
		{

			if(!field.Translatable)
				return;

			XmlElement node = document.CreateElement(FieldName, string.Empty);

			node.SetAttribute(FileId, field.ID.ToString());
			node.InnerText = field.Value;

			owner.AppendChild(node);

		}
	}
}
